import type { CSSProperties, FC } from 'react'
import { memo } from 'react'
import { useDrag, useDrop } from 'react-dnd'

import { ItemTypes } from './ItemTypes'

const style: CSSProperties = {
  border: '1px dashed gray',
  padding: '0.5rem 1rem',
  marginBottom: '.5rem',
  backgroundColor: 'white',
  cursor: 'move',
}

export interface CardProps {
  originalIndex:number,
  item: any,
  moveCard: (id: string, to: number) => void
  findCard: (id: string) => { index: number }
}

interface Item {
  id: string
  originalIndex: number
}

export const Card: FC<CardProps> = memo(function Card({
 item,
  moveCard,
  findCard,
  originalIndex,
}) {
  console.log({item,originalIndex})
  // const originalIndex = findCard(item.id).index
  const [{ isDragging }, drag] = useDrag(
    () => ({
      type: ItemTypes.CARD,
      item: { id:item.id, originalIndex },
      collect: (monitor) => ({
        isDragging: monitor.isDragging(),
      }),
      end: (item2, monitor) => {
        const { id: droppedId, originalIndex } = item2
        const didDrop = monitor.didDrop()

        if (!didDrop) {
          moveCard(droppedId, originalIndex)
        }
      },
    }),
    [item.id, originalIndex, moveCard],
  )

  const [, drop] = useDrop(
    () => ({
      accept: ItemTypes.CARD,
      drop(item2:any, monitor) {
        console.log('item.id2222',item.id)
        const { index: overIndex } = findCard(item.id)
        moveCard(item.id, overIndex)
        //  console.log({item,id,monitor})
      },
      hover({ id: draggedId }: Item, monitor) {
        console.log('item.id',item.id)
        if (draggedId !== item?.id && draggedId) {
          const { index: overIndex } = findCard(item.id)

          moveCard(draggedId, overIndex)
        }
      },
    }),
    [findCard, moveCard],
  )
  const _moveCard = ()=>{
    debugger
    
  }
  const _findCard = ()=>{
    return {}
  }
  const opacity = isDragging ? 0 : 1
  return (
    <div ref={(node) => drag(drop(node))} style={{ ...style, opacity }}>
      {item.text}
      {item.list &&<ul> {item.list.map((item2,index) => {
        console.log({item2,index})
        return <Card  
        item={item2}
        originalIndex={index}
        moveCard={_moveCard}
        findCard={_findCard} />
      })}</ul>} 

      
    </div>
  )
})
